package com.A21MobileSales.JsonServices;

import java.io.IOException; 
import java.util.ArrayList;
import java.util.Arrays;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils; 

import android.app.Activity;

import com.A21.Object.MSTUser;
import com.A21.Object.MSTUserHolder;
import com.A21.Object.UploadResult;
import com.A21.Object.UploadResultHolder;
import com.A21MobileSales.DataBase.DatabaseHelper;
import com.A21MobileSales.DataBase.MyClass;
import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;
 

public class Upload {
	
	DatabaseHelper objDataHelper;
	Activity _Activity;
	String _UserName, _PassWord;

	public Upload(Activity _activity, String _userName, String _password) {
		_Activity = _activity;
		_UserName = _userName;
		_PassWord = _password;
	}
	
	public void PostTransaction(String XmlData) throws Exception {
		String URL = MyClass.getSettingstrDownlaodurl() +"?module=post"; 
		//ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); 
		//params.add(new BasicNameValuePair("XMLData",XmlData));
		//JSONArray JAryRefNo = JSONParserPost.makeHttpRequest(URL, "POST", params); 
		String RetVal="";
		HttpClient httpclient = new DefaultHttpClient();
		HttpPost httppost = new HttpPost(URL); 
		try {
		    StringEntity se = new StringEntity(XmlData, HTTP.UTF_8);
		    se.setContentType("text/xml");
		    httppost.setEntity(se); 
		    HttpResponse httpresponse = httpclient.execute(httppost);
		    HttpEntity resEntity = httpresponse.getEntity();
		    String JsonString=EntityUtils.toString(resEntity) ; 
		    String ErrMsg="";
		    if(JsonString.contains("<!DOCTYPE html>")){
		    	ErrMsg= JsonString.substring(JsonString.indexOf("<title>")+ "<title>".length(),JsonString.indexOf("</title>"));
		    }
		    if(!ErrMsg.equals("")){ 
		    	 throw new Exception(ErrMsg);
		    }
		    
		    JsonString = "{\"UploadResultfields\":" + JsonString + "}";
		    UploadResultHolder data = new Gson().fromJson(JsonString,
		    		UploadResultHolder.class);
			ArrayList<UploadResult> lists = new ArrayList<UploadResult>(
					Arrays.asList(data.UploadResultfields));
			objDataHelper = new DatabaseHelper(_Activity);
			objDataHelper.UpdatePostedHeaders(lists);  
		      
		} catch (ClientProtocolException e) { 
		    throw e;
		} catch (IOException e) { 
			 throw e;
		}  
	}
	
}
